import 'package:get/get.dart';
import 'package:xin_he/page/home/model/xin_he_goods_item_detail_entity.dart';
import 'package:flutter/material.dart';
import 'package:xin_he/utils/xin_he_UI_constancs.dart';
import '../../../../service/xin_he_reqest.dart';
import '../../../../utils/xin_he_event_bus.dart';
import '../../../../utils/xin_he_storage.dart';
import '../../../../utils/xin_he_toast.dart';
import '../../../goods/xin_he_good_detail/xin_he_goods_specification_model_entity.dart';
import '../../../mine/xin_he_adress_management/model/xin_he_address_item_model_entity.dart';
import '../../xin_he_instant_pay/xin_he_instant_pay_view.dart';
import 'xin_he_instant_buy_state.dart';

class XinHeInstantBuyLogic extends GetxController {
  final XinHeInstantBuyState state = XinHeInstantBuyState();

  Rx<XinHeGoodsItemDetailEntity> itemModel = XinHeGoodsItemDetailEntity().obs;
  RxInt count = 1.obs;
  Rx<XinHeAddressItemModelEntity> addressModel = XinHeAddressItemModelEntity().obs;

  Rx<XinHeGoodsSpecificationModelEntity> specM = XinHeGoodsSpecificationModelEntity().obs;
  RxString addressStr = '请选择地址'.obs;

  RxList specList = [].obs;


  RxInt type = 0.obs;/// 0加购物车 1立即购买

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    var arg = Get.arguments;
    if(arg != null) {
      itemModel.value = arg['goodsModel'];
      specList.value = arg['specM'];
      ///重置status
      for(XinHeGoodsSpecificationModelEntity e in specList.value) {
        e.isSelected = false;
      }
      type.value = arg['type'];
    }

    bus.on(XinHeStorage.settingDefaultAddress, (arg) {
      requestDefaultAddress();
    });

    requestDefaultAddress();
  }

  ///默认地址
  requestDefaultAddress() async {
    var userId = await XinHeLocalStorage.get(XinHeStorage.userId);

    Map<String,dynamic> param = {
      'userId': userId
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/address/findDefaultAddress',params: param,isPost: false);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }

    XinHeAddressItemModelEntity model = XinHeAddressItemModelEntity.fromJson(result.data['data']);
    addressModel.value = model;

    String ss = model.name! + model.province!+ model.city!+ model.area!+model.detail!;
    addressStr.value = ss;
  }

  ///查询商品规格
  requestGoodSpecification()async{
    Map<String,dynamic> ss = {
      'goodsId': 123
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/goodsPrice/queryGoodsPrice',params: ss,isPost: true);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }



  }

  void handleItemCount(double price,bool isAdd){

    if(isAdd){
      count.value ++;
    }else {
      if(count.value==1)return;
      count.value--;
    }

    state.totalPrice.value = count.value*price;


  }

  void reCalculateTotalAmount(double price) {
    state.totalPrice.value = count.value*price;
  }

  buyNow(XinHeGoodsItemDetailEntity model,int coun) async{
    // Map<String,dynamic> ss = {
    //   'goodsId':model.id,
    //   'amount':coun,
    //   'goodsPriceId':model.priceId,
    //   'orderType':'COMMON',
    //   'zoneType':model.goodsZoneType??0
    // };

    var userId = await XinHeLocalStorage.get(XinHeStorage.userId);
    Map<String,dynamic> ss = {
      'userId': userId,
      'amount':coun,
      'addressId':addressModel.value.id,
      'price':model.price!*coun,
      'goodsId':model.id,
      'goodsPriceId':specM.value.id!,
      'orderType':'COMMON',
      'remark':'',
    };

    // XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/shopcart/saveBuyNow',params: ss,isPost: true);
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/order/saveOrderBuy',params: ss,isPost: true);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }
    if(result.data['code'] == 0){
      Get.back();
      var ss = result.data['data'];
      Get.bottomSheet(XinHeInstantPayPage(
        zoneType: model.goodsZoneType,
        totalPrice:state.totalPrice.value,
        count: count.value,
        order: ss,
        scene: PayScene.fromGoodsDetailDirect,),
        persistent: false,isScrollControlled: true,);
    }
  }


  /// 获取价格范围
  getMaxMinPrice(List list) {
    List newList = [];
    newList.addAll(list);
    newList.sort((a, b) =>
      a.price!.compareTo(b.price!)) ;
    return '${newList[0].price} ~ ${newList.last.price}';
  }


  addToCart(XinHeGoodsItemDetailEntity model) async{

    var userId = await XinHeLocalStorage.get(XinHeStorage.userId);

    Map<String,dynamic> ss = {
      'goodsId':model.id,
      'amount':count.value,
      'goodsPriceId':specM.value.id,
      'orderType':'COMMON',
      'userId':  userId,
      'zoneType':model.goodsZoneType??0
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/shopcart/saveShopcart',params: ss,isPost: true);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }

    if(result.data['code'] == 0){
      bus.emit(XinHeStorage.refreshCart);

      XinHeToast.center('已加入到购物车');
    }
    Get.back();


  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }
}
